<template>
  <div class="wrapper">
    <div class="img-wrapper">
      <img src="http://dryl.isart.me/1604556895413bsa7p3u8.png" class="img" alt="">
      <div class="timer">
        <span>距开始</span>
        <span class="time" id="day" >{{ day }}</span>
        <span>天</span>
        <span class="time" id="hour">{{ hour }}</span>
        <span>时</span>
        <span class="time" id="min">{{ min }}</span>
        <span>分</span>
        <span class="time" id="second">{{ second }}</span>
        <span>秒</span>
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
export default {
  name: 'App2',
  setup() {
    const state = reactive({
      day: 0,
      hour: 0,
      min: 0,
      second: 0
    })
    onMounted(() => {
      const endDate = new Date('2020-11-11 00:00:00')
      const nowDate = new Date().getTime()
      let timer = parseInt((endDate - nowDate) / 1000)

      const formatTimes = (val) => val < 10 ? `0${val}` : val

      const formatTime = (timer) => {
        let day = 0,
          hour = 0,
          min = 0,
          second = 0;
        second = timer
        if (second > 60) {
          min = parseInt(second / 60)

          second = parseInt(second % 60)

          if (min > 60) {
            hour = parseInt(min / 60)

            min = parseInt(min % 60)

            if (hour > 24) {
              day = parseInt(hour / 24)

              hour = parseInt(hour % 24)
            }
          }
        }
        state.second = formatTimes(second)
        state.min = formatTimes(min)
        state.hour = formatTimes(hour)
        state.day = formatTimes(day)
      }

      if (timer > 0) {
        setInterval(() => {
          formatTime(--timer)
        }, 1000)
      }
    })

    return {
      ...toRefs(state)
    }
  }
}
</script>

<style lang="scss" scoped>
  .wrapper {
    width: 98%;
    margin: 10px auto;
    .img-wrapper {
      background: #eeeeee;
      box-sizing: border-box;
      margin-top: 20px;
      position: relative;
      width: 100%;
      overflow: hidden;
      height: 0;
      padding-bottom: 42%;
      .img {
        width: 100%;
        height: auto;
      }
    }
    .timer {
      display: flex;
      position: absolute;
      align-items: center;
      bottom: 18px;
      right: 10px;
      z-index: 9999;
      font-size: 12px;
      color: #ffffff;
      .time {
        margin: 0 2px;
        padding: 2px 4px;
        border-radius: 2px;
        box-sizing: border-box;
        background: #ffffff;
        font-weight: bold;
        color: rgba(0,139,172,1);
        font-size: 12px;
      }
    }
  }
</style>